<template>
  <a-form-model
    ref="ruleForm"
    class="AsteriskAfter newEditStyle rightDrawerWithoutCol"
    style="display:flex;flex-direction: column;"
  >
    <a-form-model-item
      :label="$t('versionDetail')"
      class="customFormModelItem"
    >
    </a-form-model-item>
    <!-- 版本信息 -->
    <version-infor :recordData="recordData"/>

     <!-- SVN地址 -->
    <a-form-model-item v-if="recordData.svnPath" label="SVN地址" class="customFormModelItem"> 
    <div>
      <a-row :gutter="20">
        <a-col :span="18">
          <a-input disabled v-model="recordData.svnPath"  placeholder="单行输入"></a-input>
        </a-col
      >
      <a-col :span="4">
         <a-switch  style="margin-top:4px" checked-children="启用" un-checked-children="暂停" :checked="pathStatus"  @click="handlerIsGetResourceByPath"></a-switch>
      </a-col>
      </a-row>
    </div>
    </a-form-model-item>
    <!-- 升级文件 -->
    <a-form-model-item
      label="升级文件-全包"
      class="customFormModelItem"
      style="margin-top:24px"
    >
      <div>
        <template v-if="entirePackage">
          <span style="margin-right: 10px;">{{entirePackage.name || '--'}}</span>
          <auth-text :auth="softwarePerms.partsSoftware.delete" style="margin-right: 20px" v-if="editable"
                     @click="$refs.onlineModel.deleteEntirePackage(entirePackage.id, ()=>{entirePackage=null;recordData.refreshData()})">
            <a-tooltip :title="$t('delete')"><a-icon type="close"/></a-tooltip>
          </auth-text>
<!--          <hr style="border:none;border-top:1px dashed black;"/>-->
          <a-divider />
          <p>
            <b style="margin-right: 15px">详情</b>
            <auth-text v-if="editable" :auth="softwarePerms.partsSoftware.packageConfig" @click="handleEdit(entirePackage)">{{ $t('edit') }}</auth-text>
          </p>
          <detail>
            <detail-item :label="$t('fileSize')" :content="entirePackage.file.size|renderSize"/>
            <detail-item :label="$t('fileStatus')" >
              <span>{{ entirePackage.fileStatusStr }}</span>
              <a-tooltip placement="top" style="margin-left: 5px" v-if="entirePackage.showFaildReason">
                  <template slot="title">
                    {{ entirePackage.faildReason }}
                  </template>
                  <a-icon type="exclamation-circle" :style="{ color: 'red' }"/>
              </a-tooltip>
            </detail-item>
            <detail-item :label="$t('zysf')" :content="digestAlgorithm[entirePackage.file.hashAlgorithm]"/>
            <detail-item :label="$t('zyz')" :content="entirePackage.file.checksum"/>
            <detail-item :label="$t('estimatedInstallTime')" :content="entirePackage.installTime + 's'"/>
            <detail-item :label="$t('timeout')" :content="entirePackage.overTime + 's'"/>
            <detail-item :label="$t('dllFileClassName')" v-if="!dllName" :content="dllClassNameDictCodeObj[entirePackage.dllName]"/>
            <detail-item :label="$t('softFormNo')" v-if="entirePackage.versionPhase === 'PROD'" :content="entirePackage.softFormNo"/>
          </detail>
        </template>
        <template v-else>
          无
          <a-button style="margin-left: 100px" @click="handleAdd({key:'1'}, {resourceType:'10'})"
                    v-if="$hasPermission([softwarePerms.partsSoftware.packageConfig]) && editable">上传全包</a-button>
        </template>
      </div>
    </a-form-model-item>
    <a-form-model-item
      label="升级文件-差分包"
      class="customFormModelItem"
      style="margin-top:24px"
    >
    </a-form-model-item>
    <div
      class="tablePageWarp"
      style="padding:0;flex:1 0 0"
    >
      <div class="table-page-search-wrapper commonSelectWidth">
          <a-row :gutter="16">
            <a-col :md="8">
              <VersionSelect v-model="queryParam.sourceVersionId" :clear="true" :onlyVersionType="recordData.versionType === 'TEST' ? '' : 'PROD'"
                             :ecuModuleId="recordData.ecuModuleId"
                             :targetVersionId="recordData.id"
              />
            </a-col>
            <a-col
              :md="12"
              :sm="24"
              class="btnWarp" style="margin-top: 0"
            >
              <div class="searchBtns">
              <a-button-group>
                <a-button @click="refreshData" type="primary" >
                  <i class="iconfont icon-chazhao"></i>
                  {{ $t('inquiry') }}
                </a-button>
                <a-button @click="initClear">
                  <i class="iconfont icon-qingkong"></i>
                  {{ $t('clear') }}
                </a-button>
              </a-button-group>
                <a-dropdown v-if="$hasPermission([softwarePerms.partsSoftware.packageConfig]) " v-model="menuVisible">
                  <a-menu
                    slot="overlay"
                    @click="(e) =>handleAdd(e, {resourceType:'20'})"
                  >
                    <a-menu-item key="1">
                      {{ $t('uploadFile') }}
                    </a-menu-item>
                    <a-menu-item key="2" v-if="recordData.formType!=='AUTO'">
                      {{$t('onlineProduction')}}
                    </a-menu-item>
                  </a-menu>
                  <a-button type="primary">
                    <i class="iconfont icon-xinjian"></i>
                    {{ $t('file') }}
                    <span style="fontSize:1.4rem;margin-left:6px">
                      <a-icon
                        v-if="menuVisible"
                        type="down"
                      />
                      <a-icon
                        v-else
                        type="right"
                      />
                    </span>
                  </a-button>
                </a-dropdown>
              </div>
            </a-col>
          </a-row>
      </div>
      <s-table
        ref="table"
        size="default"
        :rowKey="(record,index)=>record.id"
        :columns="operColumns"
        :data="loadData"

        :scroll="{x:true}"
        :draggable="false"
      >
      <!-- class="h100 withMinHeightTbodyBox" -->
      <!-- :scrollX="1050" -->
        <template
          slot="packageName"
          slot-scope="text,record"
        >
          <a v-if="$hasPermission([softwarePerms.partsSoftware.partPackageDownload]) && record.createBy == userId
            && record.process === 100 && !record.downloading" @click="download(record)">{{record.name}}</a>
          <table-ellipsis v-else :text="record.name"></table-ellipsis>
          <span v-if="record.downloading">下载中...</span>
        </template>
        <template
          slot="strSize"
          slot-scope="text,record"
        >
          <table-ellipsis :text="record.file.size|renderSize"></table-ellipsis>
        </template>
        <!-- 文件进度 -->
        <template
          slot="fileProcess"
          slot-scope="text,record"
        >
          <a @click="showProcess(record)">
            <a-progress :percent="text" :show-info="false" />
          </a>
        </template>
        <template
          slot="fileStatus"
          slot-scope="text,record"
        >
          <span>{{ record.fileStatusStr }}</span>
          <a-tooltip placement="right" v-if="record.showFaildReason" style="margin-left: 5px">
              <template slot="title">
                {{ record.faildReason }}
              </template>
              <a-icon type="exclamation-circle" :style="{ color: 'red' }"/>
          </a-tooltip>
        </template>
        <template
          slot="uploadTime"
          slot-scope="text"
        >
          <table-ellipsis :text="text?$options.filters.moment(text):'-'"></table-ellipsis>
        </template>
        <!-- 文件类型 -->
        <!-- <template
          slot="fileType"
          slot-scope="text,record"
        >
          <table-ellipsis :text="$t(typeList.filter(item=>item.value===`${record.resourceType}`)[0].key)">
          </table-ellipsis>
        </template> -->
        <template
          slot="sourceVersion"
          slot-scope="text, record"
        >
          <template>
            <table-ellipsis
              v-if="record.sourceVersionName"
              :text="record.sourceVersionName || $t('none')"
            ></table-ellipsis>
            <span v-else>{{ $t('none') }}</span>
          </template>
        </template>
        <!-- 预计安装时间 -->
        <template
          slot="installTime"
          slot-scope="text"
        >
          <table-ellipsis :text="text"></table-ellipsis>
        </template>
        <template
          slot="overTime"
          slot-scope="text"
        >
          <table-ellipsis :text="text"></table-ellipsis>
        </template>
        <!-- <template
          slot="dllName"
          slot-scope="text"
        >
          <table-ellipsis :text="dllNameDictCodeObj[text]"></table-ellipsis>
        </template> -->
        <template
          slot="zyz"
          slot-scope="text,record"
        >
          <a @click="showZyz(record)">{{ $t('view') }}</a>
        </template>
        <template
          slot="zysf"
          slot-scope="text,record"
        >
          {{ digestAlgorithm[record.hashAlgorithm] }}
        </template>
        <template
          slot="action"
          slot-scope="text, record"
        >
          <auth-text @click="download(record)" style="padding-right:4px"
                     :disabled="!$hasPermission(softwarePerms.partsSoftware.partPackageDownload) || record.createBy != userId
                      || record.process !== 100 || record.downloading">{{ $t('download') }}</auth-text>
          <span v-if="record.downloading">下载中...</span>
          <auth-text :auth="softwarePerms.partsSoftware.packageConfig" style="padding-right:4px"
                      v-if="record.resourceState === 3 && record.onlineDiff === true && !record.retrying"
                      @click="handleRetry(record)">{{ '重试' }}</auth-text>
          <span v-if="record.retrying">重试中...</span>
          <!-- 删除和编辑 -->
        <!--   <auth-text :auth="softwarePerms.partsSoftware.packageConfig" v-if="editable" @click="handleEdit(record)">{{ $t('edit') }}</auth-text>
          <auth-text :auth="softwarePerms.partsSoftware.packageConfig" v-if="editable" @click="deleteList(record)">
            {{ $t('delete') }}
          </auth-text> -->
        </template>
      </s-table>
    </div>
    <!-- 上传文件，在线制作，编辑弹框 -->
    <upload-upgrade-package
      ref="uploadModel"
      :dllName="dllName"
      :recordData="recordData"
      :newFileType="newFileType"
      @refreshData="()=>{getEntirePackage();refreshData();}"
      @refreshSoftVersion="refreshSoftVersion"
    ></upload-upgrade-package>

    <!-- 在线制作 -->
    <online-make-package
          ref="onlineModel"
          :recordData="recordData"
          @refreshData="refreshData"
          @refreshSoftVersion="refreshSoftVersion"
          @refreshVersion="getEntirePackage"
        ></online-make-package>

    <!-- 摘要值弹框 -->
    <summary-modal ref="summaryRef" :summaryValue="summaryValue">
    </summary-modal>
    <!-- 升级进度弹框 -->
    <process-file ref="processRef" :processId="processId"></process-file>
  </a-form-model>

</template>
<script>
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import VersionInfor from './VersionInfor.vue'
import AuthText from '@/components/AuthText'
import { softwarePerms } from '@/config/permission/index'
import { STable } from '@/components'
import { mapState } from 'vuex'
import UploadUpgradePackage from './UploadUpgradePackage.vue'
import { typeList, fileConfigurationColumns } from './config'
import OnlineMakePackage from './OnlineMakePackage.vue'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import SummaryModal from '@/views/components/SummaryModal.vue'
import VersionSelect from '@/views/components/VersionSelect'
import DetailItem from '@/components/detail/detailItem'
import Detail from '@/components/detail'

import ProcessFile from './ProcessFile.vue'
import fileApi from "@api/modules/system/fileUpload";
import {downloadBlobFile} from "@/utils/functions";
import {axios} from "@/utils/request";
export default {
  name: 'VersionFile',
  components: {
    Detail,
    DetailItem,
    TableEllipsis,
    HasNoPermissionTip,
    VersionInfor,
    AuthText,
    STable,
    UploadUpgradePackage,
    OnlineMakePackage,
    QuestionMarkTip,
    VersionSelect,
    SummaryModal,
    ProcessFile
  },
  props: {
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    ...mapState({
      instantUpdateTime: (state) => state.app.instantUpdateTime,
      fileStatusDictCode: (state) => state.dict.fileStatusDictCode,
      userId: (state) => state.user.userId,
      digestAlgorithm: (state) => state.dict.digestAlgorithm
    }),
    editable() {
      if (!this.recordData.id) {
        //新增
        return true;
      }
      //升级包配置/详情，必须是测试版
      return this.recordData.versionType === 'TEST';
    },
    dllClassNameDictCodeObj () {
      return this.$store.getters.getDictCodeObj('dllClassNameDictCode')
    },
    dllNameDictCodeObj () {
      return this.$store.getters.getDictCodeObj('dllNameDictCode')
    },
    fileStatusDictCodeObj () {
      return this.$store.getters.getDictCodeObj('fileStatusDictCode')
    },
    resourceStateDictCodeObj () {
      return this.$store.getters.getDictCodeObj('resourceStateDictCode')
    }
  },
  data () {
    return {
      dllName: undefined,
      columns: fileConfigurationColumns,
      entirePackage:null,
      softwarePerms,
      pageSize: 20,
      queryParam: {},
      newFileType: '1',
      menuVisible: false,
      typeList,
      summaryValue: '', // 摘要值
      timer: null,
      processId: '',
      deleteId: [],
      baseUri: process.env.NODE_ENV === 'development' ? '/baseApi' : process.env.VUE_APP_API_BASE_URL,
      pathStatus:this.recordData.svnEnabled
    }
  },
  watch: {
    instantUpdateTime: {
      handler () {
        const vm = this
        this.$refs.table && this.refreshData(true)
        this.operColumns = this.$commonFun.deepCopy(vm.columns).filter(item=>{
          return item.key!=='fileType'
        })
        console.log( this.operColumns);
        if (this.editable) {
          this.operColumns.splice(this.operColumns.length - 1, 1);
        }
        this.operColumns.push(
          {
            title: this.$t('operation'),
            dataIndex: 'action',
            width: 120,
            fixed: 'right',
            scopedSlots: { customRender: 'action' }
          }
        );
        this.getEntirePackage();
      },
      immediate: true
    }
    // drawerMainOpened: {
    //   handler (val) {
    //     const vm = this
    //     if (val) {
    //       this.timer = window.setInterval(function () {
    //         vm.$refs.table.refresh()
    //       }, 10000)
    //     } else {
    //       vm.timer && clearTimeout(this.timer)
    //     }
    //   },
    //   immediate: true
    // }
  },
  mounted () {
    this.$store.dispatch('getDllClassNameDictCodeData')
    this.$store.dispatch('getDllNameDictCodeData')
    this.$store.dispatch('getFileStatusDictCodeData')
    this.$store.dispatch('getResourceStateDictCodeData')
    this.$api.versionInfor({ id: this.recordData.id }).then(res => {
      this.dllName = res.data.dllName
    })
  },
  methods: {
    loadData (parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      // let versionType = this.recordData.versionType;
      // if (versionType === 'TEST') {
      //   //测试版本可以看所有类型原始版本（的差分包）
      //   versionType = null;
      // }
      JnqueryParam.targetVersionId = vm.recordData.id
      // JnqueryParam.versionType = versionType;//测试版/定版
      JnqueryParam.resourceType = 20;//差分包
      return vm.$api.getResourceList({ ...parameter, ...JnqueryParam }).then(res => {
                res.data.forEach((item,index) =>{
                  item = this.fileStatusFaildShow(item)
                  item = { ...item, downloading: false }
                })
                return res
             })
    },
    fileStatus (record) {
      let str = ''
      //  已认可
      if (record.approved) {
        str = this.$t('ApproveYes')
      } else {
        str = this.fileStatusDictCodeObj[record.file.status]
        // 加密情况
        str = str + '(' + this.resourceStateDictCodeObj[record.resourceState] + ')'
      }
      return str
    },
    //启用或暂停svnPath获取包
    handlerIsGetResourceByPath(){  
      this.pathStatus=!this.pathStatus;
     this.$api.isGetResourceByPath({
      targetVersionId: this.recordData.id,
      enabled:this.pathStatus,
      svnPath:this.recordData.svnPath
      }).then(res=>{
      console.log(res);
       this.recordData.refreshData();
      })}
    ,
    fileStatusFaildShow(item){
      item.fileStatusStr = this.fileStatus(item)
      item.showFaildReason = false
      // 加密失败，并且有结果
      if(item.resourceState == 3 && item.faildReason){
         item.showFaildReason = true
      }
      return item
    },
    getEntirePackage(){
      this.$api.getResourceList({
        pageNo: 1,
        pageSize: 10,
        targetVersionId: this.recordData.id,
        resourceType: 10 //全包
      }).then(res => {
        if (!res.data || res.data.length === 0) {
          this.entirePackage = null;
          return;
        }
        if (res.data.length > 1) {
          this.$message.error('当前版本存在多个全包！')
          return;
        }
        res.data[0] = this.fileStatusFaildShow(res.data[0])
        this.entirePackage = res.data[0];
      })
    },
    // 上传文件 在线制作差分包
    handleAdd (e, config) {
      const vm = this
      vm.newFileType = e.key
      vm.$nextTick(() => {
        // vm.$refs.uploadModel.handleAdd()
        if(e.key == 1){
          vm.$refs.uploadModel.handleAdd(config)
        }else{
          //在线制作需要判断ECU满不满足
          if (this.recordData.ecu.encryptType === 0) {
            this.$message.warning(vm.$t('nosupportFeature'))
            return;
          }
          vm.$refs.onlineModel.handleAdd()
        }
      })
    },
    // 重试
    handleRetry (record) {
      record.retrying = true
      this.$api.diffRetry({ id:record.id }).then(() => {
        this.$message.success('重试成功')
        this.refreshData() // 刷新列表
      }).finally(()=>{
        record.retrying = false
      })
    },
    // 编辑
    handleEdit (record) {
      const vm = this
      // eslint-disable-next-line no-param-reassign
      record.enabled = `${record.enabled}`
      vm.$nextTick(() => {
        vm.$refs.uploadModel.handleEdit(record)
      })
    },
    // 展示摘要值
    showZyz (record) {
      this.summaryValue = record.checksum
      this.$refs.summaryRef.visible = true
    },
    deleteList (record) {
      const vm = this
      vm.deleteId = [record.id]
      this.$confirm({
        title: vm.$t('delete'),
        content: vm.$t('deleteVersionTip'),
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk: vm.deleteListOk,
        onCancel () { }
      })
    },
    deleteListOk () {
      const vm = this
      vm.$api.deleteResource({ ids: vm.deleteId }).then(() => {
        vm.$message.success(vm.$t('successfullyDelete'))
        vm.refreshData() // 刷新页面
        vm.refreshSoftVersion() // 刷新软件版本列表更新全量包列和差分包个数列
      })
    },
    initClear () {
      this.queryParam = {}
      this.refreshData(true)
    },
    refreshData (bool = false) {
      this.$refs.table.refresh(bool)
    },
    // 刷新软件版本列表
    refreshSoftVersion () {
      this.recordData.refreshData()
    },
    showProcess (record) {
      this.processId = record.id
      this.$refs.processRef.visible = true
    },
    download (record) {
      this.$set(record, 'downloading', true)
      this.axios({
        url: '/file-service/file/download/resource/'+ record.id,
        method: 'post',
        // params,
        responseType: 'blob'
      }).then((res) => {
        downloadBlobFile(res, record.name)
      }).finally(() => {
        this.$set(record, 'downloading', false)
      })
    }
  }
}
</script>
<style lang="less">
  .itemInfor {
    padding: 8px 0;
    position: relative;
    .Inforlabel {
      position: absolute;
      left: 0;
      top: 0;
      display: inline-block;
      width: 92px;
    }
    .Inforcontent {
      padding-left: 90px;
    }
  }
</style>
